import os
import sys
import re
# import file
import configparser
import threading
import time
import queue
import subprocess
from multiprocessing import Process, Queue
import json
import random
import warframeWin
import wx


def get_ping_result(ip_address):
    p = subprocess.Popen(["ping.exe", ip_address], stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
    out = p.stdout.read().decode('gbk')
    #  # print("获取输出的ping内容")
    #  # print(out)
    reg_receive = '已接收 = \d'
    match_receive = re.search(reg_receive, out)
    receive_count = -1
    if match_receive:
        receive_count = int(match_receive.group()[6:])
    if receive_count > 0:  # 接受到的反馈大于0，表示网络通 其次 可以单独控制是否全部请求通过 以及延迟时间
        reg_min_time = '最短 = \d+ms'
        reg_max_time = '最长 = \d+ms'
        reg_avg_time = '平均 = \d+ms'
        match_min_time = re.search(reg_min_time, out)
        min_time = int(match_min_time.group()[5:-2])
        match_max_time = re.search(reg_max_time, out)
        max_time = int(match_max_time.group()[5:-2])
        match_avg_time = re.search(reg_avg_time, out)
        avg_time = int(match_avg_time.group()[5:-2])
        return [receive_count, min_time, max_time, avg_time]
    else:
        # print('网络不通，目标服务器不可达！')
        return [0, 9999, 9999, 9999]


ping_result = []
# {id:"",delay}


def runProces(processID, name, ipCont, qApi):
    '''锁定进程 多进程同步调用 适合多数据处理控制使用'''
    # global ping_result
    #  # print("sad")
    # ipCont = ipCont
    # pingCmds = "ping " + ipCont
    # ipResult = os.popen(pingCmds)
    # resd = ipResult.read()
    get_result = get_ping_result(ipCont)
    # if get_result[0] > 0:
    print("输出 ping结果数据")
    print(processID,  name,  ipCont, str(get_result))
    # ping_result.append({"id": ipCont, "delay": get_result[3]})
    qApi.put({"id": ipCont, "delay": get_result})
    # '''此处调用线程run部分代码'''


# threadLock = threading.Lock()

# getIpList = []

globalID = ""
globalDelay = ""


class warframeIp():
    initpath = ""
    warFrameList = []
    warFrameDomain = []

    def __init__(self, parent):
        # print('是否执行' + str(self))
        #  ui_index.MyFrame1.__init__(self, parent)
        curpath = os.path.dirname(os.path.realpath(__file__))
        initpath = os.path.join(curpath, "config.ini")
        self.initpath = initpath
        cof1 = configparser.ConfigParser()
        cof1.read(initpath, encoding="utf-8")
        sections = cof1.sections()
        # "warFrameIPList"
        if "warFrameIPList" in sections[0]:
            # options = cof1.options(sections[0])
            items1 = cof1.get(sections[0], "ip")
            items2 = cof1.get(sections[0], "conf")
            #  # print(sections)
            #  # print(options)
            # print(items1)
            # print(items2)
            self.warFrameList = items1.split(",")
            self.warFrameDomain = items2.split(",")
    # def main(parameter_list):
    #   pass

    def rePings(self):
        # global ping_result
        # global ping_result
        # print("hosttext")
        '''添加多线程同步执行 ping获取结果逻辑'''
        # sys.sy
        getIpList = self.warFrameList
        processID = 1
        tName = "thread-"+str(processID)
        procesdList = []
        qApi = Queue()
        for val in getIpList:
            ipCont = val
            # procesd = myProcess(processID, tName, ipCont)
            procesd = Process(target=runProces, args=(
                processID, tName, ipCont, qApi))
            procesdList.append(procesd)
            processID += 1
            tName = "thread-"+str(processID)
            procesd.start()
        ping_result = []
        for thd in procesdList:
            thd.join()
            # print("挂掉了1")
            rsult = qApi.get()
            # print("挂掉了2")
            # print(rsult)
            # rsult["delay"][0]
            # rsult["delay"][3]
            if rsult["delay"][0] > 0 and rsult["delay"][3] < 250:
                ping_result.append(rsult)
         # print("主进程获取子进程数据")
        # 此处获取内容成功，然后排序
        for idx in range(len(ping_result)):
            # print("循环1")
            # print(idx)
            for idx1 in range(len(ping_result)):
                if idx + 1 < len(ping_result) and idx1 > idx:
                    if ping_result[idx]["delay"][3] > ping_result[idx1]["delay"][3]:
                        obj1 = json.loads(json.dumps(ping_result[idx1]))
                        obj2 = json.loads(json.dumps(ping_result[idx]))
                        ping_result[idx] = obj1
                        ping_result[idx1] = obj2
                        #  # print(str(self.ping_result))
                        #  # print(resd)
                        #             数据包: 已发送 = 4，已接收 = 4，丢失 = 0 (0% 丢失)，
                        # 往返行程的估计时间(以毫秒为单位):
                        #     最短 = 111ms，最长 = 113ms，平均 = 112ms
                        # api.warframe.com
                        # origin.warframe.com
        #  # print("循环结束排序内容:")
        #  # print(ping_result)
        #  # print(len(ping_result))
        self.reWriteHost(ping_result)

    def reWriteHost(self, ping_result):
        '''此处函数负责写入host内容'''
        global globalID
        global globalDelay
        # globalDelay
        # print(ping_result)
        getNumber = ping_result[0]
        # id delay
        getID = getNumber["id"]
        globalID = getID
        globalDelay = getNumber["delay"][3]
        warFrameDomainList = self.warFrameDomain
        hostText = open(r'C:\WINDOWS\system32\drivers\etc\HOSTS', 'r')
        lines = hostText.readlines()
        # print("输出获取的文件内容")
        # print(lines)
        hostText.close()
        writeHost = open(r'C:\WINDOWS\system32\drivers\etc\HOSTS', 'w+')
        domainIndex = []
        get_contsText = ""
        for val in warFrameDomainList:
            #  # print("输出匹配的 val内容")
            get_conts = writeHost.readlines()
            print("输出获取的文件内容")
            print(lines)
            for idx in range(len(lines)):
                if lines[idx] == "\n":
                    lines[idx] = ""
                if val in lines[idx]:
                    print("输出的匹配内容:")
                    print(val, lines[idx])
                    lines[idx] = ""
                    get_contsText = ''.join(lines)
                    # writeHost.write(get_contsText)
                    # else:
                    # 此处判断未匹配 对应域名
                    # "\n{0} {1}".format(getID, val)
                    # else:
                    #     get_contsText = ''.join(lines)
                    #     print("提前写入的内容:", get_contsText)
                    #     get_contsText = get_contsText + "\n{0} {1}".format(getID, val)
                    #     writeHost.write(get_contsText)
                    # getIndex = lines.index(val)
                    # 循环结束后重新写入 当前domain列表
        for dm in warFrameDomainList:
            get_contsText = get_contsText + "\n{0} {1}".format(getID, dm)
        writeHost.write(get_contsText)
        # dm
        writeHost.close()
        # {'id': '223.119.134.20', 'delay': [4, 32, 43, 36]


# def tryWriteHosts():

    # # api.warframe.com,origin.warframe.com
class WxFrames(warframeWin.MyFrame1):
    def __init__(self, parent):
        print('是否执行' + str(self))
        warframeWin.MyFrame1.__init__(self, parent)

    def btn1(self, parent):
        global frameBox
        global globalID
        global globalDelay
        print("输出内容")
        print(parent)
        btn1Label = frameBox.m_button1.GetLabel()
        if "working..." in btn1Label:
            return
        else:
            frameBox.m_button1.SetLabel("working...")
            ipConf = warframeIp({})
            flagIdx = 1
            while flagIdx > 0:
                ipConf.rePings()
                print("第{0}次执行完成开始,第{1}次,当前ID:{2},平均ping值:{3}".format(
                    flagIdx, flagIdx+1, globalID, globalDelay))
                frameBox.m_staticText1.SetLabel("第{0}次执行完成开始,第{1}次,当前ID:{2},平均ping值:{3}".format(
                    flagIdx, flagIdx+1, globalID, globalDelay))
                # SetLabel
                flagIdx += 1
                time.sleep(600)

    #  if "working..." in btn1Label:
    #       return
    #   else:
    #       frameBox.m_button1.SetLabel("working...")
    # SetLabel
    # ipConf = warframeIp({})
    # flagIdx = 1
    # while flagIdx > 0:
    #     ipConf.rePings()
    #     print("第{0}次执行完成开始,第{1}次,当前ID:{2},平均ping值:{3}".format(
    #         flagIdx, flagIdx+1, globalID, globalDelay))
    #     flagIdx += 1
    #     time.sleep(600)


if __name__ == '__main__':
    # get_ping_result("223.119.134.20")
    '''单纯后台脚本执行'''
    # ipConf = warframeIp({})
    # flagIdx = 1
    # while flagIdx > 0:
    #     ipConf.rePings()
    #     print("第{0}次执行完成开始,第{1}次,当前ID:{2},平均ping值:{3}".format(
    #         flagIdx, flagIdx+1, globalID, globalDelay))
    #     flagIdx += 1
    #     time.sleep(600)
    '''可视化代码引入'''
    app = wx.App(False)
    frameBox = WxFrames(None)
    frameBox.Show(True)
    frameBox.m_button1.Bind(wx.EVT_BUTTON, frameBox.btn1)
    app.MainLoop()
    #  = warframeWin.MyFrame1(None)
    # 30分钟循环一次
    # tryWriteHosts()
